<template>
	<view>
		<!-- 顶部搜索区域 -->
		<van-search
		  :value="searchValue"
		  label="商品"
		  placeholder="请输入搜索关键词"
		  use-action-slot
			@change="onChange"
		>
		  <view slot="action" @click="onClick">搜索</view>
		</van-search>
		<!-- 搜索历史记录 -->
		<view class="search-history">
			<view>
				<text>历史搜索</text>
				<text @click="deleteSearchHistory">删除</text>
			</view>
			<view>
				<block v-for="(item, index) in searchHistoryList" :key="index">
					<button @click="gotoGoodsList(item)">{{ item }}</button>
				</block>
			</view>
		</view>
		<!-- 搜索发现 -->
		<view class="search-history">
			<view>
				<text>搜索发现</text>
			</view>
			<view>
				<block v-for="(item, index) in searchDiscoverList" :key="index">
					<button @click="gotoGoodsList(item)">{{ item }}</button>
				</block>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		onLoad() {
			this.searchValue = ''
			this.searchHistoryList = JSON.parse(uni.getStorageSync('shistory'))
		},
		onShow() {
			this.searchValue = ''
			this.searchHistoryList = JSON.parse(uni.getStorageSync('shistory'))
		},
		data() {
			return {
				// 搜索信息内容列表
				searchHistoryList: [],
				// 绑定搜索框中的值
				searchValue: '',
				// 搜索发现
				searchDiscoverList: ['笔记本', '手机', '散热器', '零食', '毛绒玩具', '行李箱', '双肩包']
			}
		},
		methods: {
			// 搜索框中内容发生改变时触发
			onChange(e) {
				this.searchValue = e.detail
			},
			// 搜索框点击时事件出发后转至商品列表页面
			onClick() {
				this.searchHistoryList.unshift(this.searchValue)
				if(this.searchHistoryList.length >= 10) this.searchHistoryList.splice(sarr.length - 1, 1)
				uni.setStorageSync('shistory', JSON.stringify([...new Set(this.searchHistoryList)]))
				uni.navigateTo({
					url: `/subpages/goodslist/goodslist?query=${ this.searchValue }`
				})
			},
			// 删除本地的历史搜索记录
			deleteSearchHistory() {
				uni.setStorageSync('shistory', JSON.stringify([]))
				this.searchHistoryList = []
			},
			// 搜索发现栏目元素被点击时触发
			gotoGoodsList(val) {
				uni.navigateTo({
					url: '/subpages/goodslist/goodslist?query=' + val
				})
			}
		}
	}
</script>

<style>
	.search-history {
		margin: 30rpx;
	}
	
	.search-history text:first-child {
		font-size: 18px;
		font-weight: 600;
	}
	
	.search-history button {
		display: inline-block;
		margin: 10rpx;
		font-size: 14px;
		border-radius: 15px;
	}
	
	.search-history view:first-child {
		display: flex;
		justify-content: space-between;
	}
	
	.van-icon {
		width: 20px;
		height: 20px;
	}
</style>
